//
//  KLMRegisterPhoneController.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/26.
//

import UIKit

import RxSwift
import RxCocoa

class KLMRegisterPhoneController: KLMBaseController {

    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var passTextField: UITextField!
    
    @IBOutlet weak var passAgainField: UITextField!
    @IBOutlet weak var codeTextField: UITextField!
//    @IBOutlet weak var nickNameField: UITextField!
    
    //注册
    @IBOutlet weak var signupBtn: UIButton!
    /// 验证码
    @IBOutlet weak var verCodeBtn: UIButton!
    
    @IBOutlet weak var eyeBtn: UIButton!
    @IBOutlet weak var eyaAgainBtn: UIButton!
    @IBOutlet weak var countryCodeLab: UILabel!
    
    @IBOutlet weak var chooseRegionLab: UILabel!
    @IBOutlet weak var emailSignUpBtn: UIButton!
    ///隐私政策
//    @IBOutlet weak var privacyView: UIView!
//    @IBOutlet weak var privacyBtn: UIButton!
//    @IBOutlet weak var privacyLinkBtn: UIButton!
//    @IBOutlet weak var agreementTipLab: UILabel!
    
    
    @IBOutlet weak var agreeBtn: UIButton!
    @IBOutlet weak var agreeLabel: UILabel!
    
    @IBOutlet weak var userPrivacyBtn: UIButton!
    @IBOutlet weak var andLabel: UILabel!
    @IBOutlet weak var privacyPolicyBtn: UIButton!
    //倒计时
    var messageTimer: Timer?
    ///当前秒
    var currentTime: Int = 60

    ///数据
    var regionName: String? {
        didSet {
            chooseRegionLab.text = regionName
        }
    }
    var regionCode: String? {
        didSet{
            countryCodeLab.text = "+\(regionCode ?? "")"
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = KLMLocalizable.LANGLOC("Sign Up with Mobile")
        
        setupUI()
        
        events()
        
        NotificationCenter.default.post(name: .loginPageRefresh, object: nil)
        
    }

    private func setupUI() {
        
        signupBtn.setBackgroundImage(UIImage.init(color: appMainThemeColor), for: .normal)
        signupBtn.setBackgroundImage(UIImage.init(color: appMainThemeColor.withAlphaComponent(0.5)), for: .disabled)
        
        signupBtn.layer.cornerRadius = signupBtn.height / 2
        signupBtn.clipsToBounds = true
//        verCodeBtn.setTitleColor(appMainThemeColor, for: .normal)
        
        ///监控输入
        Observable.combineLatest(phoneField.rx.text.orEmpty, passTextField.rx.text.orEmpty, codeTextField.rx.text.orEmpty, passAgainField.rx.text.orEmpty) { mailText, passwordText, codeText, passAgainText  in
            
            if mailText.isEmpty ||  passwordText.isEmpty || codeText.isEmpty || passAgainText.isEmpty {
                return false
            } else {
                return true
            }
        }.bind(to: signupBtn.rx.isEnabled)
            .disposed(by: disposeBag)
        chooseRegionLab.text = KLMLocalizable.LANGLOC("Please choose a region")
        signupBtn.setTitle(KLMLocalizable.LANGLOC("Sign Up"), for: .normal)
        verCodeBtn.configStyle(with: KLMLocalizable.LANGLOC("Get verification code"), font: UIFont(safeName: "PingFangSC-Medium", size: 11), titleColor: rgba(51, 51, 51, 1), bgImage: UIImage.image(withColor: rgba(239, 239, 239, 1), size: verCodeBtn.size, cornerRadius: 2))
        verCodeBtn.configStyle(titleColor: rgba(239, 239, 239, 1), state: .disabled)
        
        emailSignUpBtn.configStyle(with: KLMLocalizable.LANGLOC("Sign up with Email"), font: UIFont(safeName: "PingFangSC-Medium", size: 14), titleColor: rgba(38, 38, 38, 1))
        
        phoneField.placeholder = KLMLocalizable.LANGLOC("Mobile number")
        passTextField.placeholder = KLMLocalizable.LANGLOC("Enter password")
        passAgainField.placeholder = KLMLocalizable.LANGLOC("Enter password again")
//        nickNameField.placeholder = KLMLocalizable.LANGLOC("Enter nickname")
        codeTextField.placeholder = KLMLocalizable.LANGLOC("Enter code")
        
        eyeBtn.configStyle(image: "icon_invisible")
        eyeBtn.configStyle(image: "icon_visual", state: .selected)
        eyaAgainBtn.configStyle(image: "icon_invisible")
        eyaAgainBtn.configStyle(image: "icon_visual", state: .selected)
        
        agreeLabel.text = KLMLocalizable.LANGLOC("I agree to")
        andLabel.text = KLMLocalizable.LANGLOC("And")
//        已阅读并同意《用户协议》和《隐私政策》
        privacyPolicyBtn.configStyle(with: "《" + KLMLocalizable.LANGLOC("Privacy Policy") + "》", titleColor: rgba(28, 136, 229, 1))
        userPrivacyBtn.configStyle(with: "《" + KLMLocalizable.LANGLOC("User Protocol") + "》", titleColor: rgba(28, 136, 229, 1))
        agreeBtn.configStyle(image: "icon_no_select")
        agreeBtn.configStyle(image: "icon_select", state: .selected)
        
        // 添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapRegion(_:)))
        chooseRegionLab.isUserInteractionEnabled = true
        chooseRegionLab.addGestureRecognizer(tapGesture)
    }
    
    private func events() {
        
        ///默认填充中国
        regionCode = "86"
        regionName = KLMTool.getCountryNameByPhoneCode(phoneCode: regionCode!)
    }
    
    ///获取验证码
    @IBAction func sendCode(_ sender: UIButton) {
        
        guard let text = KLMTool.isEmptyString(string: phoneField.text) else {
            SVProgressHUD.showInfo(withStatus: phoneField.placeholder)
            return
        }
        
        if !KLMVerifyManager.isPhone(phone: text) {
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("The mobile number format is incorrect"))
            return
        }
        
        SVProgressHUD.show()
        KLMRequest.getPhoneCode(phone: text) { response in
            SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Verification code has been sent"))
            sender.isEnabled = false
            ///开始倒计时
            self.startTimer()
        } failure: { error in
            KLMHttpShowError(error)
        }

//        KLMService.getPhoneCode(phone: text) { _ in
//            
//            SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Verification code has been sent"))
//            
//            ///开始倒计时
//            self.startTimer()
//            
//        } failure: { error in
//            KLMHttpShowError(error)
//        }
    }
    
    //注册
    @IBAction func register(_ sender: Any) {
        
        //比较两次密码
        if passTextField.text != passAgainField.text {
            
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("The password entered again is different"))
            return
        }
        if agreeBtn.isSelected == false {
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Please agree to the Privacy Policy"))
            return
        }
        
        if !KLMVerifyManager.isPhone(phone: phoneField.text!) {
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("The mobile number format is incorrect"))
            return
        }
        SVProgressHUD.show()
        KLMRequest.signUp(telephone: phoneField.text!, password: passTextField.text!, code: codeTextField.text!, nickName: "") { response in
            SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
            if let loginVc = self.navigationController?.viewControllers.first(where: {$0.isKind(of: KLMLoginController.self)}) {
                self.navigationController?.popToViewController(loginVc, animated: true)
            }
        } failure: { error in
            KLMHttpShowError(error)
        }

//        KLMService.signUp(telephone: phoneField.text!, password: passTextField.text!, code: codeTextField.text!, nickName: nickNameField.text!) { _ in
//            
//            SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
//            self.navigationController?.popViewController(animated: true)
//            
//        } failure: { error in
//            KLMHttpShowError(error)
//        }
    }
    
    ///选择地区
    @objc func tapRegion(_ sender: Any) {
        
//        return
        
        let vc = KLMCountryCodeViewController()
        vc.backCountryCode = { [weak self] country, code in
            guard let self = self else { return }
            self.regionName = country
            self.regionCode = code
        }
        let nav = KLMNavigationController.init(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        present(nav, animated: true)
    }
    
    @IBAction func signUpWithEmail(_ sender: Any) {
        
//        let vc = KLMRegisterViewController()
        let vc = KLMRegisterEmailController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func startTimer() {
        
        stopTime()
        
        verCodeBtn.isEnabled = false
        messageTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(UpdateTimer), userInfo: nil, repeats: true)
    }
    
    private func stopTime() {
        currentTime = 60
        if messageTimer != nil {
            messageTimer?.invalidate()
            messageTimer = nil
        }
    }
    
    @objc func UpdateTimer() {
        
        currentTime -= 1
        verCodeBtn.setTitle(KLMLocalizable.LANGLOC("Get verification code") + "（\(currentTime)s）", for: .normal)
        if currentTime <= 0 {//结束
            stopTime()
            verCodeBtn.isEnabled = true
            verCodeBtn.setTitle(KLMLocalizable.LANGLOC("Get verification code"), for: .normal)
        }
    }
    
    @IBAction func eyeBtn(_ sender: UIButton) {
        passTextField.isSecureTextEntry = !passTextField.isSecureTextEntry
        sender.isSelected = !sender.isSelected
    }
    
    @IBAction func againEye(_ sender: UIButton) {
        passAgainField.isSecureTextEntry = !passAgainField.isSecureTextEntry
        sender.isSelected = !sender.isSelected
    }
    
    
    @IBAction func agreementClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    @IBAction func userPrivacyLink(_ sender: Any) {
        let vc = WHWebViewController()
        vc.urlString = "https://www.kinglumi.com/about/privacy-policy"
        vc.loadingProgressColor = appMainThemeColor
        navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func privacyLink(_ sender: Any) {
        let vc = WHWebViewController()
        vc.urlString = "https://www.kinglumi.com/about/privacy-policy"
        vc.loadingProgressColor = appMainThemeColor
        navigationController?.pushViewController(vc, animated: true)
    }
}
